package com.ymlyj666.onlinechat.control;

import com.alibaba.fastjson.JSON;
import com.ymlyj666.onlinechat.dao.UserDao;
import com.ymlyj666.onlinechat.model.Response;
import com.ymlyj666.onlinechat.model.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/register.do")
public class RegisterServlet extends HttpServlet {
    private UserDao userDao;

    @Override
    public void init() throws ServletException {
        super.init();
        userDao = new UserDao();
    }

    @Override
    public void destroy() {
        try {
            userDao.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        super.destroy();
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String username = req.getParameter("username");
        String password = req.getParameter("password");

        User user = new User();
        user.setUsername(username);
        user.setPassword(password);

        user = userDao.save(user);

        if (user == null) {
            resp.getWriter().print(JSON.toJSONString(new Response<>(1001, "该用户名已存在，请使用其他用户名！")));
        } else {
            user.setPassword("");
            resp.getWriter().print(JSON.toJSONString(new Response<>(user)));
        }

    }
}
